package com.simple.system.service.impl;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.simple.common.exception.ServiceException;
import com.simple.framework.constant.HttpStatus;
import com.simple.framework.core.auth.JwtContext;
import com.simple.framework.core.domain.dto.PagingDto;
import com.simple.system.domain.dto.SysPostDto;
import com.simple.system.domain.entity.SysPost;
import com.simple.system.mapper.SysPostMapper;
import com.simple.system.service.SysPostService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Description 岗位信息表(SysPost)表服务实现类
 * @Author xiaoke
 * @Date 2024/8/10 18:00
 * @Version 1.0
 */
@Service("sysPostService")
public class SysPostServiceImpl implements SysPostService {

    private final SysPostMapper sysPostMapper;

    public SysPostServiceImpl(SysPostMapper sysPostMapper) {
        this.sysPostMapper = sysPostMapper;
    }


    @Override
    public Page<SysPost> list(PagingDto dto) {
        Page<SysPost> dictionaryPage = new Page<>(dto.getPageNum(), dto.getPageSize());
        return sysPostMapper.selectPage(dictionaryPage, null);
    }

    @Override
    public SysPost findById(Long id) {
        SysPost sysPost = sysPostMapper.selectById(id);
        if (sysPost == null) {
            throw new ServiceException("岗位不存在", HttpStatus.BAD_REQUEST);
        }
        return sysPost;
    }

    @Override
    @Transactional
    public void deleteById(Long id) {
        if (sysPostMapper.findBySysPostId(id) > 0) {
            throw new ServiceException("该岗位关联了用户，不能删除");
        }
        sysPostMapper.deleteById(id);
    }

    @Override
    public Long create(SysPostDto sysPostDto) {
        SysPost sysPost = new SysPost();
        BeanUtils.copyProperties(sysPostDto, sysPost);
        //设置状态
        sysPost.setCreatorId(JwtContext.getUserId());
        sysPost.setUpdateId(JwtContext.getUserId());
        sysPostMapper.insert(sysPost);
        return sysPost.getId();
    }

    @Override
    public void updateById(Long id, SysPostDto sysPostDto) {
        SysPost sysPost = sysPostMapper.selectById(id);
        if (sysPost == null) {
            throw new ServiceException("岗位不存在", HttpStatus.BAD_REQUEST);
        }
        BeanUtils.copyProperties(sysPostDto, sysPost);
        sysPost.setUpdateId(JwtContext.getUserId());
        sysPostMapper.updateById(sysPost);
    }
}

